#include <sys/socket.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>

#include <pthread.h>

void *client_thread(void *arg) {
    int clientfd = *(int *)arg;
    while (1) {
        char buffer[128] = {0};
        int count = recv(clientfd, buffer, 128, 0);
        if (count == 0) {
            close(clientfd);
            break;
        }
        printf("recv:count:%d,buffer:%s\n", count, buffer);
        send(clientfd, buffer, count, 0);
    }
    close(clientfd);
}

int main() {
    // 0 stdin 1 stdout 2 stderr 
    int socketfd = socket(AF_INET, SOCK_STREAM, 0);
    
    struct sockaddr_in serveraddr;
    memset(&serveraddr, 0, sizeof(struct sockaddr_in));

    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
    serveraddr.sin_port = htons(2048);

    if (bind(socketfd, (struct sockaddr *)&serveraddr, sizeof(struct sockaddr)) == -1) {
        perror("bind");
        return -1;
    }
    listen(socketfd, 10);
#if 0
    struct sockaddr_in clientaddr;
    socklen_t len = sizeof(clientaddr);
    int clientfd = accept(socketfd, (struct sockaddr *)&clientaddr, &len);

#if 0
    char buffer[128];
    int count = recv(clientfd, buffer, 128, 0);
    printf("recv:count:%d,buffer:%s\n", count, buffer);

    send(clientfd, buffer, count, 0);
#else
    while (1)
    {
        char buffer[128];
        int count = recv(clientfd, buffer, 128, 0);
        if (count == 0) { // 对端调用了close
            break;
        }
        printf("recv:count:%d,buffer:%s\n", count, buffer);
        send(clientfd, buffer, count, 0);
    }
    printf("break");
#endif
#else
    while (1)
    {
        struct sockaddr_in clientaddr;
        socklen_t len = sizeof(clientaddr);
        int clientfd = accept(socketfd, (struct sockaddr *)&clientaddr, &len);

        pthread_t thid;
        pthread_create(&thid, NULL, client_thread, &clientfd);
    }
#endif
    getchar();
    close(socketfd);
    return 0;
}